<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Login extends CI_Controller {

    public function index() {
        $this->load->view('login');
    }

    public function checkLogin() {
        $name = trim(strtolower($this->input->post('txtAdminName'))); //User names are not case sensitive
        $pass = trim($this->input->post('txtAdminPass'));
        $code = strtolower($this->input->post('txtVerifyCode'));

        if (!isset($name) || $name == '' || !isset($pass) || $pass == '')
            die();

         $rst = $this->checkCode($code);
         if($rst !== 'ok') 
         {
         	die($rst);
         }

        $rst = $this->userInfo($name, $pass);
        if ($rst !== 'ok') {
            die($rst);
        }

        //写入用户操作信息
        $this->m_public->write_logs('登录系统！', '/admin.php/login');

        echo TRUE;
    }

    public function logout() {
        $this->session->set_userdata('user_name', '');
        $this->session->set_userdata('user_id', 0);
        redirect('/login');
    }

    private function checkCode($valcode) {
        if ($valcode !== strtolower($this->session->userdata['valcode'])) {
            return $this->showError(201);
        } else {
            return 'ok';
        }
    }

    private function userInfo($name, $pass) {
        $this->load->model('m_login', 'login');
        $info = $this->login->getUserInfo(array('adminname' => $name));
        if (empty($info)) {
            return $this->showError(202);
        } else {
            if ($info['adminpass'] !== md5($pass)) {
                return $this->showError(202);
            } else {
                if($info['sysroleids']){
                    $ids = explode(',',$info['sysroleids']);
                    foreach ($ids as $key => $value) {
                        if($value == '-1' || !$value){ continue;}
                        $groupname[] = $this->m_public->getRowInfo('sysrole',array('sysroleid'=>$value),'rolename');
                    }
                }
                $sess_date['user_role_name'] = $groupname;
                $sess_date['user_name'] = $info['adminname'];
                $sess_date['user_id'] = $info['adminid'];
                $this->session->set_userdata($sess_date);
                return 'ok';
            }
        }
    }

    private function showError($code) {
        switch ($code) {
            case '201':
                # code...
                return '验证码有误';
                break;
            case '202':
                # code...
                return '用户名或密码有误';
                break;
            default:
                # code...
                break;
        }
    }

}
